package com.fc.v2.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.fc.v2.common.base.BaseService;
import com.fc.v2.common.support.ConvertUtil;
import com.fc.v2.mapper.auto.*;
import com.fc.v2.mapper.custom.RoleDao;
import com.fc.v2.mapper.custom.TsysUserDao;
import com.fc.v2.model.Examine;
import com.fc.v2.model.ExpertSelect;
import com.fc.v2.model.auto.*;
import com.fc.v2.model.custom.RoleVo;
import com.fc.v2.model.custom.Tablepar;
import com.fc.v2.shiro.util.ShiroUtils;
import com.fc.v2.util.MD5Util;
import com.fc.v2.util.SnowflakeIdWorker;
import com.fc.v2.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 系统用户
 * @ClassName: SysUserService
 * @author fuce
 * @date 2018年8月26日
 *
 */
@Service
public class SysUserService implements BaseService<TsysUser, TsysUserExample>{
	//生成的用户dao
	@Autowired
	private TsysUserMapper tsysUserMapper;

	//生成的角色用户dao
	@Autowired
	private TSysRoleUserMapper tSysRoleUserMapper;

	//自定义角色dao
	@Autowired
	private RoleDao roleDao;

	//自动生成的角色dao
	@Autowired
	private TsysRoleMapper tsysRoleMapper;

	//自定义用户dao
	@Autowired
	private TsysUserDao userDao ;

	//专家选择dao
	@Autowired
	private ExperprojectMapper experprojectMapper;


	@Autowired
	private ApplyProjectService applyProjectService;

	@Autowired
	private ApplyProjectMapper applyProjectMapper;

	@Autowired
	private FinishProjectMapper finishProjectMapper;



	/**
	 * 分页查询
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	 public PageInfo<TsysUser> list(Tablepar tablepar){

		 PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
		 List<TsysUser> list= userDao.queryUserInfo(tablepar.getSearchText());
		 PageInfo<TsysUser> pageInfo = new PageInfo<TsysUser>(list);

		 return  pageInfo;
	 }
	/**
	 * 单位用户管理分页查询
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public PageInfo<TsysUser> listDanwei(Tablepar tablepar){

		PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
		//仅查询该单位的用户
		TsysUserExample testExample=new TsysUserExample();
		TsysUserExample.Criteria criteria = null;

		String userId = ShiroUtils.getUserId();
		String deptName = tsysUserMapper.selectByPrimaryKey(userId).getDeptName();
		//窗体搜索
		if(StrUtil.isNotEmpty(tablepar.getSearchText())) {
			String name = "%" + tablepar.getSearchText() + "%";
			criteria = testExample.createCriteria().andNicknameLike(name).andDeptNameEqualTo(deptName);
		}else {//大搜索
			criteria = testExample.createCriteria().andDeptNameEqualTo(deptName);
		}
		List<TsysUser> tsysUserList = new ArrayList<>();
		tsysUserList = tsysUserMapper.selectByExample(testExample);
//		List<TsysUser> list= userDao.queryUserInfo(tablepar.getSearchText());
		PageInfo<TsysUser> pageInfo = new PageInfo<TsysUser>(tsysUserList);
		return  pageInfo;
	}
	/**
	 * 个人用户管理分页查询
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public PageInfo<TsysUser> listGeren(Tablepar tablepar){

		PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
		//仅查询个人用户
		String userId = ShiroUtils.getUserId();
		TsysUser tsysUser = tsysUserMapper.selectByPrimaryKey(userId);
		List<TsysUser> list = new ArrayList<>();
		list.add(tsysUser);
//		List<TsysUser> list= userDao.queryUserInfo(tablepar.getSearchText());
		PageInfo<TsysUser> pageInfo = new PageInfo<TsysUser>(list);
		return  pageInfo;
	}

	/**
	 * 个人用户管理分页查询
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public PageInfo<TsysUser> listUserExpert(Tablepar tablepar){

		PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
		//仅查询个人用户
		String userId = ShiroUtils.getUserId();
		TsysUser tsysUser = tsysUserMapper.selectByPrimaryKey(userId);
		List<TsysUser> list = new ArrayList<>();
		list.add(tsysUser);
//		List<TsysUser> list= userDao.queryUserInfo(tablepar.getSearchText());
		PageInfo<TsysUser> pageInfo = new PageInfo<TsysUser>(list);
		return  pageInfo;
	}
	/**
	 * 专家角色查询
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public PageInfo<TsysUser> listExpert(Tablepar tablepar){
		//专家id
		TsysRoleExample tsysRoleExample = new TsysRoleExample();
		tsysRoleExample.createCriteria().andNameEqualTo("专家");
		List<TsysRole> tsysRoleList = tsysRoleMapper.selectByExample(tsysRoleExample);
		String roleId = tsysRoleList.get(0).getId();
		//所有专家角色的用户
		TSysRoleUserExample tSysRoleUserExample = new TSysRoleUserExample();
		tSysRoleUserExample.createCriteria().andSysRoleIdEqualTo(roleId);
		List<TSysRoleUser> userRoleList = tSysRoleUserMapper.selectByExample(tSysRoleUserExample);

		List<String> userIdList = new ArrayList<>();
		for (TSysRoleUser ur:userRoleList) {
			userIdList.add(ur.getSysUserId());
		}

		TsysUserExample testExample=new TsysUserExample();
		TsysUserExample.Criteria criteria = null;
		//专家名称搜索
		if(StrUtil.isNotEmpty(tablepar.getSearchText())) {//小窗体
			String name = "%"+tablepar.getSearchText()+"%";
			criteria = testExample.createCriteria().andNicknameLike(name).andIdIn(userIdList);
		} else {//大搜索
			criteria = testExample.createCriteria().andIdIn(userIdList);
		}
		//专家学历搜索
		if(StrUtil.isNotEmpty(tablepar.getSearchXueli())) {//小窗体
			criteria.andIdIn(userIdList).andUserEducationEqualTo(tablepar.getSearchXueli());}
		//专家学位搜索
		if(StrUtil.isNotEmpty(tablepar.getSearchXuewei())) {//小窗体
			criteria.andIdIn(userIdList).andUserAcademicDegreeEqualTo(tablepar.getSearchXuewei());}
		//研究专长搜索
		if(StrUtil.isNotEmpty(tablepar.getSearchExpertise())) {//小窗体
			String expertise = "%"+tablepar.getSearchExpertise()+"%";
			criteria.andIdIn(userIdList).andUserExpertiseLike(expertise);}
		//单位名称搜索
		if(StrUtil.isNotEmpty(tablepar.getSearchDeptName())) {//小窗体
			String deptName = "%"+tablepar.getSearchDeptName()+"%";
			criteria.andIdIn(userIdList).andDeptNameLike(deptName);}
		//专业职称搜索
		if(StrUtil.isNotEmpty(tablepar.getSearchTitle())) {//小窗体
			String title = "%"+tablepar.getSearchTitle()+"%";
			criteria.andIdIn(userIdList).andUserTitleLike(title);}


		PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
//		List<TsysUser> list= userDao.queryUserInfo(tablepar.getSearchText());
		List<TsysUser> list= tsysUserMapper.selectByExample(testExample);
		PageInfo<TsysUser> pageInfo = new PageInfo<TsysUser>(list);

		return  pageInfo;
	}

	/**
	 * 分页查询
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public PageInfo<TsysUser> listAvoid(Tablepar tablepar,String proId){
		PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());

		List<Experproject> list_ep = new ArrayList<>();
		ExperprojectExample example=new ExperprojectExample();
		example.createCriteria().andOther1EqualTo(ExpertSelect.EXPERT_AVOID.code).andProIdEqualTo(proId);
		list_ep = experprojectMapper.selectByExample(example);

		List<TsysUser> list_tu = new ArrayList<>();
		for (Experproject ep:list_ep) {
			TsysUser tsysUser = tsysUserMapper.selectByPrimaryKey(ep.getExpertId());
			//将Experproject对象中的other2字段装入tsysUser中不使用的username字段，用于表格显示，不会写入数据库，类似于wapper
			tsysUser.setUsername(ep.getOther2());
			list_tu.add(tsysUser);
		}
		PageInfo<TsysUser> pageInfo = new PageInfo<TsysUser>(list_tu);

		return  pageInfo;
	}



	@Override
	@Transactional
	public int deleteByPrimaryKey(String ids) {
		List<String> lista=ConvertUtil.toListStrArray(ids);
		TsysUserExample example=new TsysUserExample();
		example.createCriteria().andIdIn(lista);
		int i=tsysUserMapper.deleteByExample(example);
		if(i>0){
			TSysRoleUserExample tSysRoleUserExample=new TSysRoleUserExample();
			tSysRoleUserExample.createCriteria().andSysUserIdIn(lista);
			tSysRoleUserMapper.deleteByExample(tSysRoleUserExample);
		}
		return i;

	}

	/**
	 * 添加用户
	 */
	@Override
	public int insertSelective(TsysUser record) {
		return tsysUserMapper.insertSelective(record);
	}

	/**
	 * 添加用户跟角色信息
	 * @param record
	 * @param roles
	 * @return
	 */
	@Transactional
	public int insertUserRoles(TsysUser record,String roles) {
		String userid=SnowflakeIdWorker.getUUID();
		record.setId(userid);
		//添加更新时间
		Date date = new Date();
		Timestamp timeStamp = new Timestamp(date.getTime());
		record.setUpdateTime(timeStamp);
		if(StringUtils.isNotEmpty(roles)){
			List<String> list_roles=ConvertUtil.toListStrArray(roles);
			 for (String rolesid : list_roles) {
				 TSysRoleUser roleUser=new TSysRoleUser(SnowflakeIdWorker.getUUID(), userid,rolesid);
				 tSysRoleUserMapper.insertSelective(roleUser);
			}
		}

		//密码加密
		record.setPassword(MD5Util.encode(record.getPassword()));
		return tsysUserMapper.insertSelective(record);
	}

	/**
	 * 添加用户注册信息
	 * @param record
	 * @return
	 */
	@Transactional
	public int insertUserRegister(TsysUser record) {
		String userid=SnowflakeIdWorker.getUUID();
		record.setId(userid);
		//添加更新时间
		Date date = new Date();
		Timestamp timeStamp = new Timestamp(date.getTime());
		record.setUpdateTime(timeStamp);
		//添加用户角色
		TSysRoleUser roleUser=new TSysRoleUser(SnowflakeIdWorker.getUUID(), userid,record.getUserType());
		tSysRoleUserMapper.insertSelective(roleUser);
		//密码加密
		record.setPassword(MD5Util.encode(record.getPassword()));
		return tsysUserMapper.insertSelective(record);
	}

	/**
	 * 添加专家与立项项目映射信息
	 * @param record
	 * @param roles
	 * @return
	 */
	@Transactional
	public int insertExpertApplyProject(Experproject record,String expertIds,String proId) {
		ApplyProject applyProject = new ApplyProject();
		//赋值项目id
		applyProject.setId(proId);
		//社科联审核状态为专家审核中
		applyProject.setSklPass(Examine.EXPECT_DOING.code);
		//专家审核状态为待审核
		applyProject.setExpertPass(Examine.NEED_EXAMINE.code);
		//添加更新时间
		applyProject.setSklUpdateTime(new Date());
		applyProjectMapper.updateByPrimaryKeySelective(applyProject);
		//更新的数据总量
		int i = 0;
			if(StringUtils.isNotEmpty(expertIds)){
				List<String> list_experts=ConvertUtil.toListStrArray(expertIds);
			for (String expertId : list_experts) {
				Experproject experProject = new Experproject();
				//添加联结表id
				experProject.setId(SnowflakeIdWorker.getUUID());
				//添加专家id
				experProject.setExpertId(expertId);
				//添加项目id
				experProject.setProId(proId);
				//添加审核进度为待审核
				experProject.setCheckProcess(Examine.NEED_EXAMINE.code);
				//添加项目进程状态
				experProject.setOther1(ExpertSelect.EXPERT_APPLY.code);
				experprojectMapper.insertSelective(experProject);
				i++;
			}
		}
		return i;
	}

	/**
	 * 添加专家与结项项目映射信息
	 * @param record
	 * @param roles
	 * @return
	 */
	@Transactional
	public int insertExpertFinishProject(Experproject record,String expertIds,String proId) {
		FinishProject finishProject = new FinishProject();
		//项目Id
		finishProject.setId(proId);
		//社科联状态为专家审核中
		finishProject.setSklPass(Examine.EXPECT_DOING.code);
		//专家审核状态为待审核
		finishProject.setExpertPass(Examine.NEED_EXAMINE.code);
		finishProjectMapper.updateByPrimaryKeySelective(finishProject);
		//更新的数据总量
		int i = 0;
		if(StringUtils.isNotEmpty(expertIds)){
			List<String> list_experts=ConvertUtil.toListStrArray(expertIds);
			for (String expertId : list_experts) {
				Experproject experProject = new Experproject();
				//添加联结表id
				experProject.setId(SnowflakeIdWorker.getUUID());
				experProject.setExpertId(expertId);
				experProject.setProId(proId);
				//映射表中项目进度为结项
				experProject.setOther1(ExpertSelect.EXPERT_FINISH.code);
				experprojectMapper.insertSelective(experProject);
				//添加审核进度为待审核
				experProject.setCheckProcess(Examine.NEED_EXAMINE.code);
				i++;
			}
		}
		return i;
	}

	/**
	 * 添加回避专家与项目映射信息
	 * @param record
	 * @param roles
	 * @return
	 */
	@Transactional
	public int insertExpertAvoid(Experproject record,String expertIds,String proId,String other2s) {

		//更新的数据总量
		int i = 0;
		if(StringUtils.isNotEmpty(expertIds)){
			List<String> list_experts = ConvertUtil.toListStrArray(expertIds);
			List<String> list_other2s = ConvertUtil.toListStrArray(other2s);
			for (String other2: list_other2s) {
				for (String expertId : list_experts) {
					Experproject experProject = new Experproject();
					//添加联结表id
					experProject.setId(SnowflakeIdWorker.getUUID());
					experProject.setExpertId(expertId);
					experProject.setProId(proId);
					//设置类型为结项
					experProject.setOther1(ExpertSelect.EXPERT_AVOID.code);
					//写入回避理由
					experProject.setOther2(other2);
					experprojectMapper.insertSelective(experProject);
					i++;
					break;
				}
			}
		}
		return i;
	}



	@Override
	public TsysUser selectByPrimaryKey(String id) {

		return tsysUserMapper.selectByPrimaryKey(id);
	}


	@Override
	public int updateByPrimaryKeySelective(TsysUser record) {
		record.setPassword(MD5Util.encode(record.getPassword()));
		return tsysUserMapper.updateByPrimaryKeySelective(record);
	}





	@Override
	public int updateByExampleSelective(TsysUser record, TsysUserExample example) {

		return tsysUserMapper.updateByExampleSelective(record, example);
	}


	@Override
	public int updateByExample(TsysUser record, TsysUserExample example) {

		return tsysUserMapper.updateByExample(record, example);
	}

	@Override
	public List<TsysUser> selectByExample(TsysUserExample example) {

		return tsysUserMapper.selectByExample(example);
	}


	@Override
	public long countByExample(TsysUserExample example) {

		return tsysUserMapper.countByExample(example);
	}


	@Override
	public int deleteByExample(TsysUserExample example) {

		return tsysUserMapper.deleteByExample(example);
	}

	/**
	 * 检查用户name
	 * @param tsysUser
	 * @return
	 */
	public int checkLoginNameUnique(TsysUser tsysUser){
		TsysUserExample example=new TsysUserExample();
		example.createCriteria().andUsernameEqualTo(tsysUser.getUsername());
		List<TsysUser> list=tsysUserMapper.selectByExample(example);

		return list.size();
	}

	/**
	 * 获取所有权限 并且增加是否有权限字段
	 * @return
	 */
	public List<RoleVo> getUserIsRole(String userid){
		List<RoleVo> list=new ArrayList<RoleVo>();
		//查询出我的权限
		List<TsysRole> myRoles= roleDao.queryUserRole(userid);
		TsysRoleExample tsysRoleExample=new TsysRoleExample();
		//查询系统所有的角色
		List<TsysRole> tsysRoles=tsysRoleMapper.selectByExample(tsysRoleExample);
		if(StringUtils.isNotEmpty(tsysRoles)){
			for (TsysRole tsysRole : tsysRoles) {
				Boolean isflag=false;
				RoleVo roleVo=new RoleVo(tsysRole.getId(),tsysRole.getName(), isflag);
				for (TsysRole myRole : myRoles) {
					if(tsysRole.getId().equals(myRole.getId())){
						isflag=true;
						break;
					}
				}
				if(isflag){
					roleVo.setIscheck(true);
					list.add(roleVo);
				}else{
					list.add(roleVo);
				}
			}
		}
		return list;
	}


	/**
	 * 修改用户密码
	 * @param record
	 * @return
	 */
	public int updateUserPassword(TsysUser record) {
		record.setPassword(MD5Util.encode(record.getPassword()));
		//修改用户信息
		return tsysUserMapper.updateByPrimaryKeySelective(record);
	}


	/**
	 * 修改用户信息以及角色信息
	 * @param record
	 * @param roles
	 * @return
	 */
	@Transactional
	public int updateUserRoles(TsysUser record,String roleIds) {
		//先删除这个用户的所有角色
		TSysRoleUserExample tSysRoleUserExample=new TSysRoleUserExample();
		tSysRoleUserExample.createCriteria().andSysUserIdEqualTo(record.getId());
		tSysRoleUserMapper.deleteByExample(tSysRoleUserExample);
		if(StringUtils.isNotEmpty(roleIds)) {
			List<String> list_roles=ConvertUtil.toListStrArray(roleIds);
			//添加新的角色信息
			for (String role : list_roles) {
				TSysRoleUser tSysRoleUser= new TSysRoleUser(SnowflakeIdWorker.getUUID(), record.getId(), role);
				tSysRoleUserMapper.insertSelective(tSysRoleUser);
			}
		}
		//修改用户信息
		return tsysUserMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 不修改角色信息，仅修改用户信息
	 * @param record
	 * @param roles
	 * @return
	 */
	@Transactional
	public int updateUser(TsysUser record,String roleIds) {

		//修改用户信息
		return tsysUserMapper.updateByPrimaryKeySelective(record);
	}



}
